//
//  YZKCarouselPicView.m
//  xiwu
//
//  Created by yzk on 14-10-9.
//  Copyright (c) 2014年 cooperLink. All rights reserved.
//

#import "YZKCarouselPicView.h"
#import "UIImageView+WebCache.h"
#import "Utils.h"
#import "StyledPageControl.h"

@interface YZKCarouselPicView ()
<UIScrollViewDelegate>

//@property (nonatomic,retain) UIPageControl  *pageControl;
@property (nonatomic, retain) StyledPageControl *pageControl;

@end

@implementation YZKCarouselPicView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator   = NO;
        _scrollView.delegate                       = self;
        _scrollView.pagingEnabled                  = YES;
        _scrollView.bounces                        = NO;
        [self addSubview:_scrollView];

        _pageControl = [[StyledPageControl alloc] initWithFrame:CGRectMake(0, frame.size.height - 20, frame.size.width, 15)];
        _pageControl.userInteractionEnabled = NO;
        _pageControl.hidesForSinglePage = YES;
        _pageControl.pageControlStyle = PageControlStyleThumb;
        _pageControl.selectedThumbImage = [UIImage imageNamed:@"icon_carouse_current"];
        _pageControl.thumbImage = [UIImage imageNamed:@"icon_carouse_normal"];
        [self addSubview:_pageControl];
    }

    return self;
}

#pragma mark picture clicked

- (void)UesrClicked:(UITapGestureRecognizer *)sender
{
    UIView *view = sender.view;

    if (self.delegate && [self.delegate respondsToSelector:@selector(carouselPicView:didClickedPicAtIndex:)]) {
        [self.delegate carouselPicView:self didClickedPicAtIndex:view.tag];
    }
}

#pragma mark - public method

//刷新界面
- (void)reloadData
{
    self.pageControl.numberOfPages = (int)_dataArray.count;
    [self.scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

    if (_dataArray.count <= 0) {
        return;
    } else if (_dataArray.count == 1) {
        CarouselPicModel *model = _dataArray[0];

        UIImageView *imgView = [[UIImageView alloc] init];
        imgView.contentMode  = UIViewContentModeScaleToFill;
        imgView.tag          = 0;
        imgView.frame        = CGRectMake(0, 0, self.scrollView.width, self.scrollView.height);
//        imgView.image        = model.image;
        [imgView sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
        imgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]
                                             initWithTarget:self
                                                     action:@selector(UesrClicked:)];
        [imgView addGestureRecognizer:singleTap];
        [self.scrollView addSubview:imgView];
    } else {
        for (int i = 0; i < _dataArray.count; i++) {
            CarouselPicModel *model = _dataArray[i];

            UIImageView *imgView = [[UIImageView alloc] init];
            imgView.contentMode  = UIViewContentModeScaleToFill;
            imgView.tag          = i;
            imgView.frame        = CGRectMake((i + 1) * self.scrollView.width, 0, self.scrollView.width, self.scrollView.height);
//            imgView.image        = model.image;
            [imgView sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
            imgView.userInteractionEnabled = YES;
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]
                                                 initWithTarget:self
                                                         action:@selector(UesrClicked:)];
            [imgView addGestureRecognizer:singleTap];
            [self.scrollView addSubview:imgView];
        }

        for (int i = 0; i < 2; i++) {
            UIImageView *imgView = [[UIImageView alloc] init];
            imgView.contentMode  = UIViewContentModeScaleToFill;
            imgView.userInteractionEnabled = YES;
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]
                                                 initWithTarget:self
                                                         action:@selector(UesrClicked:)];
            [imgView addGestureRecognizer:singleTap];
            [self.scrollView addSubview:imgView];

            if (i == 0) {
                CarouselPicModel *model = [_dataArray lastObject];
                imgView.tag          = _dataArray.count - 1;
                imgView.frame        = CGRectMake(0, 0, self.scrollView.width, self.scrollView.height);
//                imgView.image        = model.image;
                [imgView sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
            } else {
                CarouselPicModel *model = [_dataArray firstObject];
                imgView.tag          = 0;
                imgView.frame        = CGRectMake((_dataArray.count + 1) * self.scrollView.width, 0, self.scrollView.width, self.scrollView.height);
//                imgView.image        = model.image;
                [imgView sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
            }
        }

        self.scrollView.contentSize = CGSizeMake(self.scrollView.width * (_dataArray.count + 2), self.scrollView.height);
        [self.scrollView setContentOffset:CGPointMake(self.scrollView.width, 0) animated:NO];
        [self createTimer];
    }
}

- (void)dealloc
{
    [self deleteTimer];
}

- (void)deleteTimer
{
    [_productsTimer invalidate];
}

- (void)createTimer
{
    if (_productsTimer) {
        [_productsTimer invalidate];
    }

    _productsTimer = [NSTimer scheduledTimerWithTimeInterval:TimeInterval
                                                      target:self
                                                    selector:@selector(onProductsTimer:)
                                                    userInfo:nil
                                                     repeats:YES];
}

- (void)startTimer
{
    [_productsTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:TimeInterval]];
}

- (void)pauseTimer
{
    [_productsTimer setFireDate:[NSDate distantFuture]];
}

#pragma mark - private method


- (void)onProductsTimer:(NSTimer *)timer
{
    if (self.pageControl.numberOfPages == 0) {
        return;
    }

    [self slidingForward];
}

- (void)slidingForward
{
    int pageWidth = self.scrollView.frame.size.width;
    int index = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;

    index++;

    CGPoint offset = CGPointMake(self.scrollView.width * index, 0);
    [self.scrollView setContentOffset:offset animated:YES];
}

#pragma mark - scrollView Delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    float pageWidth = scrollView.frame.size.width;
    int index = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;

    int virtualIndex = index - 1;

    if (self.pageControl.currentPage == virtualIndex) {
        return;
    }

    self.pageControl.currentPage = virtualIndex;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self pauseTimer];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self startTimer];

    int pageWidth = scrollView.frame.size.width;
    int index = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;

    if (index == 0) {
        index = (int)self.dataArray.count;
        CGPoint offset = CGPointMake(self.scrollView.width * index, 0);
        [scrollView setContentOffset:offset animated:NO];
    } else if (index == self.dataArray.count + 1) {
        index = 1;
        CGPoint offset = CGPointMake(self.scrollView.width * index, 0);
        [scrollView setContentOffset:offset animated:NO];
    }

    self.pageControl.currentPage = index - 1;
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    int pageWidth = scrollView.frame.size.width;
    int index = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;

    if (index == 0) {
        index = (int)self.dataArray.count;
        CGPoint offset = CGPointMake(self.scrollView.width * index, 0);
        [scrollView setContentOffset:offset animated:NO];
    } else if (index == self.dataArray.count + 1) {
        index = 1;
        CGPoint offset = CGPointMake(self.scrollView.width * index, 0);
        [scrollView setContentOffset:offset animated:NO];
    }

    self.pageControl.currentPage = index - 1;
}

@end
